﻿using AutoMapper;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Infratrveture;
using B.S.Filtration.Read.Api.Application.Command.ContactPhone;
using B.S.Filtration.Read.Api.Dto;
using Dapper;
using MediatR;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ContactPhone
{
    public class GetContactPhoneHander : IRequestHandler<GetContactPhoneCommand, APIPaging<List<ContactPhoneDto>>>
    {

        private readonly IMapper mapper;
        private readonly DapperContext db;

        public GetContactPhoneHander(IMapper mapper, DapperContext db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 显示供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<ContactPhoneDto>>> Handle(GetContactPhoneCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<ContactPhoneDto>> paging = new APIPaging<List<ContactPhoneDto>>();

            var offset = (request.PageIndex - 1) * request.PageSize;

            // 使用参数化查询来防止 SQL 注入
            var parameters = new DynamicParameters();
            parameters.Add("PageSize", request.PageSize);
            parameters.Add("Offset", offset);

            // 基础查询语句
            string baseQuery = "FROM ContactPhones WHERE 1=1";

            // 添加 ContactId 条件
            if (request.ContactId.HasValue)
            {
                baseQuery += " AND ContactId = @ContactId";
                parameters.Add("ContactId", request.ContactId.Value);
            }

            // 总计数查询
            string totalCountQuery = $"SELECT COUNT(*) {baseQuery}";
            paging.TotalCount = await db.QuerySingleAsync<int>(totalCountQuery, parameters);

            // 数据查询
            string listQuery = $"SELECT * {baseQuery} ORDER BY ContactId ASC LIMIT @Offset, @PageSize";
            var result = await db.QueryAsync<ContactPhoneDto>(listQuery, parameters);
            paging.data = result.ToList();

            paging.TotalPage = (int)Math.Ceiling((double)paging.TotalCount / request.PageSize);

            return paging;
        }
    }
}

